#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List, Dict, Any
from pydantic import BaseModel
from fastapi import APIRouter
from agents.second_bargaining_agent.dispatch_agent import DispatchAgent, DispatchRequest
from agents.second_bargaining_agent.fill_agent import FillAgent, FillRequest
from agents.second_bargaining_agent.globalqaagent import GlobalQARequest, GlobalQAgent
from agents.second_bargaining_agent.save_agent import SaveAgent, SaveRequest
from models.doubao import logger
from agents.second_bargaining_agent.status_confirmation_Agent import StatusAgent, StatusRequest


class SecondBargainingRequest(BaseModel):
    """统一API请求模型"""
    form: Dict[str, Any] = {}
    conversations: List[Dict[str, str]]
    status: str = "1"
    category: str  = "无"
    subcategory: str | None = ""
    cooperation_status: str | None = ""


class SecondBargainingResponse(BaseModel):
    """统一API响应模型"""
    form: Dict[str, Any] = {}
    is_manual: bool = False
    agent_response: str | None = ""
    status: str = "0"  # 定义为字符串类型
    reference: str | None = ""
    category: str | None = ""
    subcategory: str | None = ""
    cooperation_status: str | None = ""



class SecondBargainingService:
    """统一服务,封装三个智能体的完整流程"""

    def __init__(self):
        self.dispatch_agent = DispatchAgent()
        self.fill_agent = FillAgent()
        self.save_agent = SaveAgent()
        self.status_confirmation_agent = StatusAgent()
        self.globalqa_agent = GlobalQAgent()
        self.router = APIRouter(prefix="/secondbargaining")
        self._setup_routes()
        logger.info("Initialized SecondBargainingService")

    def _setup_routes(self) -> None:
        """设置路由"""
        self.router.post("/process", response_model=SecondBargainingResponse)(self.process_request)

    async def process_request(self, request: SecondBargainingRequest) -> SecondBargainingResponse:
        """处理统一API请求"""
        try:
            dispatch_request = DispatchRequest(
                conversations=request.conversations
            )

            dispatch_response = await self.dispatch_agent.dispatch_route(dispatch_request)

            if not dispatch_response.success:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response="好的宝",
                    status="1"  # 正确：字符串类型
                )

            route_code = dispatch_response.route_code
            logger.info(f"Dispatch agent returned route code: {route_code}")

            if route_code == "1":
                return await self._handle_fill_agent(request)
            elif route_code == "2":
                return await self._handle_global_qa(request)
            elif route_code == "3":
                return SecondBargainingResponse(
                    agent_response="好的,清单已确认,后续将按此推进合作",
                    form=request.form,
                    status="0",  # 正确：字符串类型
                    category="无",
                    subcategory="已确认",
                    cooperation_status="确认合作"
                )
            else:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response="好的 宝子",
                    status="0"  # 正确：字符串类型
                )

        except Exception as e:
            logger.error(f"Error processing unified request: {str(e)}")
            return SecondBargainingResponse(
                form=request.form,
                agent_response="好的呀 宝子",
                status="1",  # 正确：字符串类型
                category=request.category,
                subcategory=request.subcategory,
                cooperation_status=request.cooperation_status
            )

    async def _handle_fill_agent(self, request: SecondBargainingRequest) -> SecondBargainingResponse:
        """处理选号智能体流程"""
        try:
            fill_request = FillRequest(
                conversations=request.conversations,
                # form=request.form
            )

            fill_response = await self.fill_agent.fill_route(fill_request)

            if not fill_response.success:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response="好的",
                    status="1"  # 正确：字符串类型
                )
            request.conversations.append({"role": "assistant", "content": fill_response.response})

            save_request = SaveRequest(
                conversations=request.conversations,
                form=request.form
            )

            save_response = await self.save_agent.save_route(save_request)
            logger.info(f"豆包回答: {fill_response.response}")
            logger.info(f"表单:{save_response.updated_form}")
            logger.info(f"聊天记录:{request.conversations}")

            if not save_response.success:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response=fill_response.response,
                    # 修复：将整数转换为字符串
                    status=str(fill_response.status),
                    category=request.category,
                    subcategory=request.subcategory,
                    cooperation_status=request.cooperation_status
                )

            status_request = StatusRequest(
                conversations=request.conversations,
                form=request.form,
                category=request.category,
                subcategory=request.subcategory,
                cooperation_status=request.cooperation_status
            )
            status_response = await self.status_confirmation_agent.status_route(status_request)
            if not status_response.success:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response=fill_response.response,
                    # 修复：将整数转换为字符串
                    status=str(fill_response.status),
                    category=request.category,
                    subcategory=request.subcategory,
                    cooperation_status=request.cooperation_status
                )

            logger.info(f"合作状态:{status_response.updated_cooperation_status}")
            logger.info(f"无法合作原因:{status_response.updated_category}")
            logger.info(f"小类:{status_response.updated_subcategory}")
            if status_response.updated_category!="无" or status_response.updated_category!="":
                if status_response.updated_subcategory in["账号异常","调性不匹配","品牌有负面","产品调性和达人不符","需求不匹配","不接报备","不接非报备","不接该类产品","近期不接广","排竞时长不满足","返点不满足","场地不符合","内容形式不符","数据不保证","需求不满足","预算不足","无真人出镜","档期不满足"]:
                    status_response.updated_cooperation_status="已拒品"
                    fill_response.status=0
            if request.category!="" or request.category!="无":
                status_response.updated_cooperation_status = "已拒品"
                fill_response.status = 0
            if status_response.updated_cooperation_status=="沟通中":
                status_response.updated_subcategory="博主权益落实中"
            if status_response.updated_cooperation_status=="确认合作":
                status_response.updated_subcategory="已确认"
                fill_response.status = 0
            print(status_response.updated_cooperation_status)
            print(status_response.updated_category)
            print(status_response.updated_subcategory)
            return SecondBargainingResponse(
                form=save_response.updated_form,
                agent_response=fill_response.response,
                category=status_response.updated_category,
                subcategory=status_response.updated_subcategory,
                cooperation_status=status_response.updated_cooperation_status,
                # 修复：将整数转换为字符串
                status=str(fill_response.status)
            )

        except Exception as e:
            logger.error(f"Error in fill agent flow: {str(e)}")
            return SecondBargainingResponse(
                form=request.form,
                agent_response=fill_response.response,
                # 修复：将整数转换为字符串（注意：需确保fill_response在异常时仍可访问）
                status=str(fill_response.status) if 'fill_response' in locals() else "1",
                reference="666",
                category=request.category,
                subcategory=request.subcategory,
                cooperation_status=request.cooperation_status
            )

    async def _handle_global_qa(self, request: SecondBargainingRequest) -> SecondBargainingResponse:
        """处理全局QA智能体流程"""
        try:
            qa_request = GlobalQARequest(
                conversations=request.conversations
            )
            qa_response = await self.globalqa_agent.qa_route(qa_request)
            if not qa_response.success:
                return SecondBargainingResponse(
                    form=request.form,
                    agent_response=qa_response.response,
                    is_manual=qa_response.is_manual,
                    reference=qa_response.reference,
                    status="1",  # 正确：字符串类型
                    category=request.category,
                    subcategory=request.subcategory,
                    cooperation_status=request.cooperation_status
                )
            logger.info(f"全局QA回答: {qa_response.response}")
            logger.info(f"转人工: {qa_response.is_manual}")
            logger.info(f"参考信息: {qa_response.reference}")
            return SecondBargainingResponse(
                form=request.form,
                is_manual=qa_response.is_manual,
                agent_response=qa_response.response,
                status="1",  # 正确：字符串类型
                reference="666",
                category=request.category,
                subcategory=request.subcategory,
                cooperation_status=request.cooperation_status
            )
        except Exception as e:
            logger.error(f"Error in global QA flow: {str(e)}")
            return SecondBargainingResponse(
                form=request.form,
                agent_response="",
                status="1",  # 正确：字符串类型
                reference="6",
                category=request.category,
                subcategory=request.subcategory,
                cooperation_status=request.cooperation_status
            )


# 全局统一服务实例
SecondBargaining_service = SecondBargainingService()
